<template>
	<view class="artner-join__form-update e-flex e-flex-wrap e-m-t-26 e-m-b-40">
		<view class="artner-join__form-update__box e-rela e-flex-xy-center e-m-r-20" v-for="(item, index) in imgList"
			:key="index">
			<image mode="aspectFill" :src="item.path" :style="{
					width,
					height
				}" @tap="previewImage(item.path)"></image>
			<image src="../../static/close.png" class="artner-join__form-update__close img-40 e-abso"
				@tap="delImg(index)"></image>
		</view>
		<view class="artner-join__form-update__box e-flex-xy-center  text-center" v-show="imgList.length < max"
			@tap="upload">
			<view>
				<view class="e-flex-x-center">
					<image src="../../static/update.png" class="artner-join__form-update__icon"></image>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref,onMounted } from 'vue'
	import { uploadFilePath } from '@/common/request/api'
	import { useCurrentInstance } from '@/common/hooks';
	import { chooseImage } from '@/common/utils';

	const props = defineProps({
		value:String,
		max: {
			type: Number,
			default: 9
		},
		width: {
			type: String,
			default: '180rpx'
		},
		height: {
			type: String,
			default: '180rpx'
		},
		count: {
			type: Number,
			default: 1
		}

	})

	const emit = defineEmits({
		change: (str : string) => true
	})
	
	const ctx = useCurrentInstance()

	const imgList = ref<{
		url : string
		path : string
	}[]>([])


	const upload = () => {
		chooseImage({
			count: props.count
		}).then(res => {
			if (res) {
				res.tempFiles.forEach(items => {
					uploadFilePath(items.tempFilePath).then(data => {
						imgList.value.push({
							url: data.data.url,
							path: items.tempFilePath
						})
						emit('change', imgList.value.map(item => item.url).join(','))
					})
				})

			}
		})
	}
	const previewImage = (urls : string) => {
		uni.previewImage({
			current: 1,
			urls: [urls]
		})
	}
	const delImg = (index : number) => {
		imgList.value.splice(index, 1)
		emit('change', imgList.value.map(item => item.url).join(','))
	}
	const addImg = (url:string) => {
		imgList.value = url.split(',').map(item => {
			return {
				url: ctx.$fullLink(item),
				path: ctx.$fullLink(item)
			}
		})
	}
	
	onMounted(() => {
		if(props.value){
			addImg(props.value)
		}
	})
	
	defineExpose({
		addImg
	})
</script>

<style lang="scss" scoped>
	.artner-join__form-update {
		&__box {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 20rpx;
			border-radius: 8rpx;
			border: 2rpx solid #e2dfe2;
		}

		&__icon {
			width: 200rpx;
			height: 200rpx;
		}

		&__close {
			top: 0rpx;
			right: 0rpx;
		}
	}
</style>